package com.demo.config.handler;

import com.demo.common.constant.JWTConstants;
import com.demo.common.model.BusinsesEnum;
import com.demo.common.model.R;
import com.demo.common.utils.JWTUtils;
import com.demo.common.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
    登出成功处理器
 */
@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        // 从请求同中 Authorization 的值
        String authorizationValue = request.getHeader(JWTConstants.AUTHORIZATION);
        if (!StringUtils.hasText(authorizationValue)){
            ResponseUtils.writeJson(response, R.FAIL(BusinsesEnum.TOKEN_EMPTY));
            return;
        }
        // 从authorizetion 的值获取令牌 token
        String jwt_token = authorizationValue.replaceFirst(JWTConstants.BEARER, "");

        // 将令牌 token 从redis 中删除
        Boolean flag = redisTemplate.delete(JWTConstants.JWT_REDIS_KEY_PREFIX + jwt_token);
        System.out.println(flag);
        // 响应数据
        ResponseUtils.writeJson(response, R.OK("退出登录成功……"));
    }
}
